
import time
import threading


class ReadWriteLock:
    def __init__(self):
        self._read_ready = threading.Condition(threading.Lock())
        self._readers = 0

    def acquire_read(self):
        with self._read_ready:
            self._readers += 1

    def release_read(self):
        with self._read_ready:
            self._readers -= 1
            if self._readers == 0:
                self._read_ready.notify_all()

    def acquire_write(self):
        self._read_ready.acquire()
        while self._readers > 0:
            self._read_ready.wait()

    def release_write(self):
        self._read_ready.release()


# 使用示例
data = []
rwlock = ReadWriteLock()


def reader(reader_id):
    for i in range(5):
        rwlock.acquire_read()
        try:
            print(f"Reader {reader_id} read: {data}")
            time.sleep(0.1)
        finally:
            rwlock.release_read()
        time.sleep(0.2)


def writer(writer_id):
    for i in range(3):
        rwlock.acquire_write()
        try:
            item = f"data_{writer_id}_{i}"
            data.append(item)
            print(f"Writer {writer_id} wrote: {item}")
            time.sleep(0.3)
        finally:
            rwlock.release_write()
        time.sleep(0.5)


# 创建读写线程
readers = []
for i in range(4):
    t = threading.Thread(target=reader, args=(i,))
    readers.append(t)
    t.start()

writers = []
for i in range(2):
    t = threading.Thread(target=writer, args=(i,))
    writers.append(t)
    t.start()

# 等待所有线程完成
for t in readers + writers:
    t.join()

print("Final data:", data)